package com.kamistoat.meimeistore.ware.listener;

import com.kamistoat.common.To.RabbitMQTo.OrderTo;
import com.kamistoat.common.To.RabbitMQTo.StockLockedTo;
import com.kamistoat.meimeistore.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    // 2分钟时主动检查是否解锁库存
    @RabbitHandler
    public void handleStockLockedRelease(Message message, StockLockedTo stockLockedTo, Channel channel){
        System.out.println("获取到库存延时工单");
        // 向RabbitMQ手动进行ack
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.stockLockedRelease(stockLockedTo);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicReject(deliveryTag, true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    // 收到订单服务通知时立刻解锁库存
    @RabbitHandler
    public void handleOrderRelease(Message message, OrderTo orderTo, Channel channel){
        System.out.println("发现订单被关闭，准备解锁库存");
        // 向RabbitMQ手动进行ack
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            wareSkuService.orderRelease(orderTo);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicReject(deliveryTag, true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
